package com.mm.cloth;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import com.bumptech.glide.Glide;
import com.mm.cloth.model.Clothes;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ClothesDetailActivity extends AppCompatActivity {

    private static final String TAG = "ClothesDetailActivity";

    // UI组件
    private ImageView btnBack;
    private ImageView clothesImage;
    private TextView tvName;
    private TextView tvCategoryTag;
    private TextView tvSeasonTag;
    private TextView tvStyleTag;
    private TextView tvMaterial;
    private TextView tvBrand;
    private TextView tvPurchaseDate;
    private TextView tvPrice;
    private LinearLayout materialLayout;
    private LinearLayout brandLayout;
    private LinearLayout purchaseDateLayout;
    private LinearLayout priceLayout;
    private LinearLayout notesLayout;
    private TextView tvNotes;
    private Button btnDelete;
    private Button btnEdit;
    
    // 数据
    private Clothes clothes;
    private int clothesId;
    
    // 季节映射
    private String[] seasonIds = {"spring", "summer", "autumn", "winter", "all"};
    private String[] seasonNames = {"春季", "夏季", "秋季", "冬季", "四季"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clothes_detail);
        
        // 获取传递的衣物ID
        clothesId = getIntent().getIntExtra("clothes_id", -1);
        if (clothesId == -1) {
            Toast.makeText(this, "衣物不存在", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        
        initViews();
        setupImage();
        loadClothesData();
        setupListeners();
    }
    
    private void initViews() {
        btnBack = findViewById(R.id.btnBack);
        clothesImage = findViewById(R.id.clothesImage);
        tvName = findViewById(R.id.tvName);
        tvCategoryTag = findViewById(R.id.tvCategoryTag);
        tvSeasonTag = findViewById(R.id.tvSeasonTag);
        tvStyleTag = findViewById(R.id.tvStyleTag);
        tvMaterial = findViewById(R.id.tvMaterial);
        tvBrand = findViewById(R.id.tvBrand);
        tvPurchaseDate = findViewById(R.id.tvPurchaseDate);
        tvPrice = findViewById(R.id.tvPrice);
        materialLayout = findViewById(R.id.materialLayout);
        brandLayout = findViewById(R.id.brandLayout);
        purchaseDateLayout = findViewById(R.id.purchaseDateLayout);
        priceLayout = findViewById(R.id.priceLayout);
        notesLayout = findViewById(R.id.notesLayout);
        tvNotes = findViewById(R.id.tvNotes);
        btnDelete = findViewById(R.id.btnDelete);
        btnEdit = findViewById(R.id.btnEdit);
    }
    
    private void setupImage() {
        // 单张图片显示，不需要轮播
        // 图片将在loadClothesData中设置
    }
    
    private void loadClothesData() {
        // 显示加载中提示
        Toast.makeText(this, "加载中...", Toast.LENGTH_SHORT).show();
        
        // 模拟从服务器获取数据
        // 实际应用中应该发送网络请求获取数据
        new Thread(() -> {
            try {
                Thread.sleep(500); // 模拟网络延迟
                
                // 模拟数据
                clothes = getMockClothes(clothesId);
                
                // 准备图片（只显示一张）
                // 不再需要imageList，直接使用单张图片
                
                // 在UI线程更新视图
                runOnUiThread(() -> {
                    if (clothes != null) {
                        updateUI();
                    } else {
                        Toast.makeText(ClothesDetailActivity.this, "获取衣物信息失败", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
                
            } catch (InterruptedException e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    Toast.makeText(ClothesDetailActivity.this, "加载失败", Toast.LENGTH_SHORT).show();
                    finish();
                });
            }
        }).start();
    }
    
    private void updateUI() {
        // 设置单张图片
        if (clothes.getImageUrl() != null && !clothes.getImageUrl().isEmpty()) {
            Glide.with(this)
                    .load(clothes.getImageUrl())
                    .placeholder(R.drawable.placeholder_clothes)
                    .error(R.drawable.placeholder_clothes)
                    .into(clothesImage);
        } else {
            clothesImage.setImageResource(R.drawable.placeholder_clothes);
        }
        
        // 设置基本信息
        tvName.setText(clothes.getName());
        
        // 设置标签
        tvCategoryTag.setText(clothes.getCategory());
        tvCategoryTag.setVisibility(View.VISIBLE);
        
        // 设置季节标签
        String seasonName = "未知";
        for (int i = 0; i < seasonIds.length; i++) {
            if (seasonIds[i].equals(clothes.getSeason())) {
                seasonName = seasonNames[i];
                break;
            }
        }
        tvSeasonTag.setText(seasonName);
        tvSeasonTag.setVisibility(View.VISIBLE);
        
        // 设置样式标签
        if (clothes.getStyle() != null && !clothes.getStyle().isEmpty()) {
            tvStyleTag.setText(clothes.getStyle());
            tvStyleTag.setVisibility(View.VISIBLE);
        } else {
            tvStyleTag.setVisibility(View.GONE);
        }
        
        // 设置材质
        if (clothes.getMaterial() != null && !clothes.getMaterial().isEmpty()) {
            tvMaterial.setText(clothes.getMaterial());
            materialLayout.setVisibility(View.VISIBLE);
        } else {
            materialLayout.setVisibility(View.GONE);
        }
        
        // 设置品牌
        if (clothes.getBrand() != null && !clothes.getBrand().isEmpty()) {
            tvBrand.setText(clothes.getBrand());
            brandLayout.setVisibility(View.VISIBLE);
        } else {
            brandLayout.setVisibility(View.GONE);
        }
        
        // 设置购入日期
        if (clothes.getPurchaseDate() != null && !clothes.getPurchaseDate().isEmpty()) {
            tvPurchaseDate.setText(clothes.getPurchaseDate());
            purchaseDateLayout.setVisibility(View.VISIBLE);
            Log.d(TAG, "设置购入日期: " + clothes.getPurchaseDate());
        } else {
            purchaseDateLayout.setVisibility(View.GONE);
            Log.d(TAG, "购入日期为空，隐藏布局");
        }

        // 设置价格
        if (clothes.getPrice() > 0) {
            String priceText = String.format("¥%.2f", clothes.getPrice());
            tvPrice.setText(priceText);
            priceLayout.setVisibility(View.VISIBLE);
            Log.d(TAG, "设置价格: " + priceText);
        } else {
            priceLayout.setVisibility(View.GONE);
            Log.d(TAG, "价格为0或负数，隐藏布局: " + clothes.getPrice());
        }

        // 设置备注
        if (clothes.getNotes() != null && !clothes.getNotes().isEmpty()) {
            tvNotes.setText(clothes.getNotes());
            notesLayout.setVisibility(View.VISIBLE);
            Log.d(TAG, "设置备注: " + clothes.getNotes());
        } else {
            notesLayout.setVisibility(View.GONE);
            Log.d(TAG, "备注为空，隐藏布局");
        }
    }
    
    private void setupListeners() {
        // 返回按钮点击事件
        btnBack.setOnClickListener(v -> finish());
        
        // 编辑按钮点击事件
        btnEdit.setOnClickListener(v -> {
            Intent intent = new Intent(ClothesDetailActivity.this, EditClothesActivity.class);
            intent.putExtra("clothes_id", clothesId);
            startActivity(intent);
        });
        
        // 删除按钮点击事件
        btnDelete.setOnClickListener(v -> showDeleteConfirmDialog());
    }
    
    private void showDeleteConfirmDialog() {
        new AlertDialog.Builder(this)
                .setTitle("确认删除")
                .setMessage("确定要删除这件衣物吗？此操作不可恢复。")
                .setPositiveButton("删除", (dialog, which) -> deleteClothes())
                .setNegativeButton("取消", null)
                .show();
    }
    
    private void deleteClothes() {
        // 显示删除中提示
        Toast.makeText(this, "删除中...", Toast.LENGTH_SHORT).show();
        
        // 模拟删除操作
        // 实际应用中应该发送网络请求删除数据
        new Thread(() -> {
            try {
                Thread.sleep(1000); // 模拟网络延迟
                
                runOnUiThread(() -> {
                    Toast.makeText(ClothesDetailActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                    setResult(RESULT_OK);
                    finish();
                });
                
            } catch (InterruptedException e) {
                e.printStackTrace();
                runOnUiThread(() -> {
                    Toast.makeText(ClothesDetailActivity.this, "删除失败，请重试", Toast.LENGTH_SHORT).show();
                });
            }
        }).start();
    }
    
    // 模拟获取衣物数据
    private Clothes getMockClothes(int id) {
        String[] categories = {"上衣", "裤子", "裙子", "外套", "鞋子", "配饰"};
        String[] seasons = {"spring", "summer", "autumn", "winter", "all"};
        String[] materials = {"棉", "麻", "丝绸", "羊毛", "聚酯纤维", ""};
        String[] styles = {"休闲", "正装", "运动", "通勤", "派对", ""};
        
        String name = "衣物" + id;
        String category = categories[id % categories.length];
        String imageUrl = "https://via.placeholder.com/300/FFC0CB/000000?text=Clothes+" + id; // 使用占位图
        String season = seasons[id % seasons.length];
        String material = materials[id % materials.length];
        String style = styles[id % styles.length];
        String brand = id % 2 == 0 ? "品牌" + id : "";
        double price = id % 3 == 0 ? id * 100.0 : 0;
        String purchaseDate = id % 2 == 0 ? "2023-" + (id % 12 + 1) + "-" + (id % 28 + 1) : "";
        String notes = id % 3 == 0 ? "这是一件非常喜欢的衣物，购于某商场打折季。" : "";
        boolean autoMatting = id % 2 == 0;
        
        Clothes clothes = new Clothes(id, name, category, imageUrl, season, brand, price, purchaseDate, notes, autoMatting);
        clothes.setMaterial(material);
        clothes.setStyle(style);
        return clothes;
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 重新加载数据，以防数据被编辑
        loadClothesData();
    }
} 